<?php
/*
 *      Redistribution and use in source and binary forms, with or without
 *      modification, are permitted provided that the following conditions are
 *      met:
 *      
 *      * Redistributions of source code must retain the above copyright
 *        notice, this list of conditions and the following disclaimer.
 *      * Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following disclaimer
 *        in the documentation and/or other materials provided with the
 *        distribution.
 *      * Neither the name of the  nor the names of its
 *        contributors may be used to endorse or promote products derived from
 *        this software without specific prior written permission.
 *      
 *      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *      "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *      LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *      A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *      OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *      SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *      LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *      DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *      THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *      (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *      OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

include('autoload.php');
class ti
{
	function __construct()
	{
		# set the default properties of $ti;
		ob_start();
		session_start();
		$this->paths   = array();
		$this->swap    = array();
		$this->config  = array();
		$this->phrases = array();
		$this->queries = array();
		$this->data   =& $_REQUEST;
		$this->files  =& $_FILES;
		$this->server =& $_SERVER;
		$this->session =& $_SESSION;
		$this->cookies     =& $_COOKIE;
		$this->environment =& $_ENV;
		$this->request     =& $_REQUEST;
		$this->arguments   =& $argv;
		
		$this->path_cache = array();
		$this->url_cache  = array();
		
		# build the basic paths
		$this->paths['server.ti'] = dirname(__FILE__);	
		$this->paths['server'] = substr($this->paths['server.ti'],0,(strlen($this->paths['server.ti']) - 3));
		$this->paths['web'] = str_replace('index.php','',$this->server['PHP_SELF']);
		
		
		# include all base libraries
		#print_r($this->paths);
		include($this->paths['server.ti'].'/ti_config.php');
		include($this->paths['server'].'/config.php');
		
		include($this->paths['server.ti'].'/ti_query.php');
		include($this->paths['server.ti'].'/ti_template.php');
		include($this->paths['server.ti'].'/ti_util.php');
		include($this->paths['server.ti'].'/ti_db.php');
		include($this->paths['server.ti'].'/ti_logging.php');
		include($this->paths['server.ti'].'/ti_convert.php');
		include($this->paths['server.ti'].'/ti_query_builder.php');
		
		#	print_r($this->config);
		# set some additional configs
		$this->config['vars.request.port']   = $this->server['SERVER_PORT'];
		$this->config['vars.request.secure'] = (substr(strtolower($this->server['SERVER_PROTOCOL']),0,5) == 'https');
		$this->config['template.base'] = ($this->config['vars.request.secure'])?'https://':'http://';
		$this->config['template.base'] .= $this->server['SERVER_NAME'];
		$this->config['template.base'] .= $this->paths['web'];
		$this->swap['base'] =& $this->config['template.base'];
			
		# figure out what we're supposed to be doing
		$this->command = str_replace($this->paths['web'],'',$this->server['REQUEST_URI']);
		if($this->command.'' == '')
		{
			$this->command = $this->config['var.default_command'];
		}

		# startup various things
		ti_db::init($this);
		ti_logging::init($this);
	}
	
	function start()
	{
		$this->process_commands($this->config['var.pre_request']);
		$this->process($this->command);
	}
	
	function ajax()
	{
		$this->finish(false,true);
	}
	
	function finish($template=true,$ajax=false,$do_exit=true)
	{		
		if($template)
		{
			$this->process_commands($this->config['var.pre_template']);
			$template = new ti_template();
			echo($template->render());
			$this->process_commands($this->config['var.post_template']);
		}

		if($ajax)
		{
			$js = '';
			foreach($this->swap as $pos=>$node)
			{
				if($pos == 'js')
				{	
					$js .= addslashes($node);
				}
				else
				{
					$areas[] = "'$pos':'".($node)."'";
				}
			}
			$areas[] = "'js':'".$js."'";
			echo('{'.implode(',',$areas).'}');
		}
		
		$this->process_commands($this->config['var.post_request']);
		
		if($do_exit)
		{
			exit();
		}
	}
	
	function redirect($new_path='')
	{
		global $ti;
		ob_clean();
		header('Location: '.$ti->config['template.base'].$new_path);
		$ti->finish(false);
	}
	
	function process($command,$params=null)
	{
		global $ti;
		#echo('command is: '.$command);
		$command = explode('?',$command);
		$command = $command[0];
		$command = explode('/',$command);
		#print_r($command);
		
		if($command[0] != 'index.php' && $command[0] != '')
		{
			
			$method  = array_pop($command);
			# do this to compensate for a trailing /
			if($method == '')
			{
				$method  = array_pop($command);
			}
			$command = implode('_',$command);
			#echo('class is : '.$command);
			#exit();
			$command = new $command();
			return $command->$method($params);
		}
	}
	
	function process_commands($commands)
	{
		foreach($commands as $index=>$command)
		{
			#echo('processing: '.$command);
			$this->process($command);
		}
	}
	
	# used for navigation elements
	function command_like($compare_to)
	{
		return (substr($this->command,0,strlen($compare_to)) == $compare_to);
	}
	
	function load_lib($filename,$path)
	{
		global $ti;
		foreach($ti->config['var.namespaces'] as $ns)
		{
			#echo('looking for '.$ti->paths['server'].'/'.$ns.'/'.$path.'/libs/'.$filename.'.php'."\n<br />");
			if(file_exists($ti->paths['server'].'/'.$ns.'/'.$path.'/libs/'.$filename.'.php'))
			{
				include($ti->paths['server'].'/'.$ns.'/'.$path.'/libs/'.$filename.'.php');
				return;
			}
		}
	}
	
	function query_build($path,$name)
	{
		if(empty($this->queries[$path]))
		{
			$this->queries[$path] = array();
		}
		$this->queries[$path][$name] = new ti_query_builder();
		return $this->queries[$path][$name];
	}
	
	function query($path,$query,$data=null)
	{
		if(empty($this->queries[$path]))
		{
			$this->load_lib('queries',$path);
		}
		#echo($this->queries[$path][$query]);
		$query = new ti_query($this->queries[$path][$query]);
		$query->execute($data);
		return $query;
	}
	
	function query_keyhash($key,$path,$query,$data=null)
	{
		global $ti;
		$keyhash = array();
		$key_list = $ti->query($path,$query,$data);
		while($key_list->next())
		{
			$keyhash[$key_list->data[$key]] = true;
		}
		return $keyhash;
	}
	
	function query_row($path,$query,$data=null)
	{
		$result = $this->query($path,$query,$data);
		if($result->next())
		{
			return $result->data;
		}
		else
		{
			return null;
		}
	}
	
	function query_value($path,$query,$col,$data=null)
	{
		$result = $this->query($path,$query,$data);
		$result->next();
		if($result->next())
		{
			return $result->data[$col];
		}
		else
		{
			return null;
		}	
	}
	
	function phrase($path,$phrase,$data=null)
	{
		global $ti;
		if(empty($this->phrases[$path]))
		{
			$this->load_lib('phrases',$path);
			$this->load_lib('phrases.'.$ti->config['vars.language'],$path);
			$this->load_lib('phrases.'.$ti->config['vars.language'].'_'.$ti->config['vars.language.variant'],$path);
		}
		#echo($this->phrases[$path][$phrase]);
		if(empty($this->phrases[$path][$phrase]))
		{
			return $phrase;
		}
		
		if(is_null($data))
		{
			return $this->phrases[$path][$phrase];
		}
		else
		{
			return ti_util::swap($this->phrases[$path][$phrase],$data);
		}
	}
	
	function log($msg,$type='default')
	{
		global $ti;
		fwrite($ti->config['log.handles'][$type],$msg."\n");
	}
	
	function has_role()
	{
		global $ti;
	}
	
	function require_role()
	{
		global $ti;
	}
	
	function has_permission($perm_name)
	{
		global $ti;
		return ($ti->session['permissions'][$perm_name]);
	}
	
	function require_permission()
	{
		global $ti;
		if(!$ti->session['permissions'][$perm_name])
		{
			$ti->finish();
		}
	}
}
?>